<template>
    <div class="w-full h-100vh flex-center">
        <div
            class="w-400px box-border p-20px flex flex-col items-center shadow-2xl relative title"
        >
            <div class="font-size-24px flex items-center">
                注册账号
                <n-button
                    text
                    class="absolute right-20 gen-btn hidden"
                    @click="generateCustomer"
                >
                    <n-icon :component="ReloadCircleOutline" :size="20" />
                </n-button>
            </div>
            <div class="w-full my-20px flex flex-col gap-10px">
                <n-input
                    v-model:value="registerForm.account"
                    placeholder="账号"
                    size="large"
                    maxlength="9"
                />
                <n-input
                    v-model:value="registerForm.username"
                    placeholder="昵称"
                    size="large"
                    maxlength="15"
                />
                <n-input
                    v-model:value="registerForm.password"
                    placeholder="密码"
                    type="password"
                    size="large"
                    maxlength="15"
                />
                <n-input
                    v-model:value="confirmPassword"
                    placeholder="确认密码"
                    type="password"
                    size="large"
                    maxlength="15"
                />
                <n-input
                    v-model:value="registerForm.phone"
                    placeholder="联系电话"
                    size="large"
                    maxlength="11"
                />
                <n-input
                    v-model:value="registerForm.companyName"
                    placeholder="公司名称"
                    size="large"
                    maxlength="20"
                />
            </div>
            <div class="w-full flex gap-10px">
                <n-button
                    size="large"
                    class="flex-1"
                    :focusable="false"
                    @click="router.push({ name: 'login' })"
                >
                    返回
                </n-button>
                <n-button
                    type="primary"
                    size="large"
                    class="flex-1"
                    :focusable="false"
                    @click="handleRegister"
                >
                    注册
                </n-button>
            </div>
            <n-divider title-placement="center">
                <n-button
                    text
                    type="info"
                    :focusable="false"
                    @click="router.push({ name: 'check' })"
                >
                    已提交申请,查看是否通过?
                </n-button>
            </n-divider>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import type { Customer } from "@/service/api/types/user";
import { ReloadCircleOutline } from "@vicons/ionicons5";
import { registerCustomer } from "@/service/api/modules/customer";

import _ from "lodash";

const router = useRouter();

const ramdomGenerateCustomer = () => {
    const phonePrefixes = [
        "130",
        "131",
        "132",
        "133",
        "134",
        "135",
        "136",
        "137",
        "138",
        "139",
        "145",
        "147",
        "150",
        "151",
        "152",
        "153",
        "155",
        "156",
        "157",
        "158",
        "159",
        "166",
        "170",
        "171",
        "172",
        "173",
        "175",
        "176",
        "177",
        "178",
        "180",
        "181",
        "182",
        "183",
        "184",
        "185",
        "186",
        "187",
        "188",
        "189",
        "198",
        "199",
    ];

    const prefix = _.sample(phonePrefixes);

    let suffix = "";
    for (let i = 0; i < 8; i++) {
        suffix += _.random(0, 9);
    }
    const phone = prefix + suffix;

    const customer: Customer = {
        account: _.padStart(
            Math.floor(Math.random() * 1000000000).toString(),
            9,
            "0"
        ),
        password: "12345678",
        username: `测试用户${_.random(1, 100000)}`,
        phone: phone,
        companyName: "测试公司",
        role: "customer",
        frozen: false,
        createdDate: Date.now(),
    };
    return customer;
};

const registerForm = reactive<Customer>({
    account: "",
    password: "",
    username: "",
    phone: "",
    companyName: "",
    role: "customer",
    frozen: false,
    createdDate: Date.now(),
});
const confirmPassword = ref("");

const generateCustomer = () => {
    const customer = ramdomGenerateCustomer();
    Object.assign(registerForm, customer);
};

const validateForm = (): boolean => {
    for (const key in registerForm) {
        const typedKey = key as keyof Customer;
        if (registerForm[typedKey] === "") {
            window.NMessage.warning("请完成表单");
            return false;
        }
    }
    if (
        registerForm.account.length !== 9 ||
        registerForm.password!.length < 8
    ) {
        window.NMessage.warning("请输入9位账号和8位以上密码");
        return false;
    }
    if (registerForm.password !== confirmPassword.value) {
        window.NMessage.warning("两次输入的密码不一致");
        return false;
    }
    if (!/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(registerForm.phone)) {
        window.NMessage.warning("请输入正确的手机号");
        return false;
    }
    return true;
};

const handleRegister = async () => {
    if (!validateForm()) return;
    try {
        await registerCustomer(registerForm);
        window.NDialog.success({
            title: "消息",
            content: "已提交注册申请，请等待审批",
            closable: false,
            maskClosable: false,
            positiveText: "返回",
            onPositiveClick: () => {
                router.push({ name: "login" });
            },
        });
    } catch (error) {
        window.NMessage.error((error as Error).message);
    }
};
</script>

<style scoped>
.title:hover .gen-btn {
    display: block;
}
</style>
